package singlejartest;

import com.dukascopy.api.*;
import com.dukascopy.api.system.*;
  
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
  
/**
 *
 * @author brian
 */
public class MySystemListener implements ISystemListener {
  private Logger          logger;
  private ITesterClient   testClient;
  private int             lightReconnects   = 3;
  private String          userName          = "";
  private String          password          = "";
  private String          jnlpUrl           = "https://www.dukascopy.com/client/demo/jclient/jforex.jnlp";
  
  MySystemListener ( Logger         logger,
                     ITesterClient  client,
                     String         userName,
                     String         password ) {
    this.logger       = logger;
    this.testClient   = client;
    this.userName     = userName;
    this.password     = password;
  }
  
  /**
  * Called on new strategy start
  *
  * @param processId id of the started strategy
  */
  @Override
  public void onStart ( long processId ) {
    logger.info ( "Strategy started: " + processId );
  }
  
  /**
  * Called on the strategy stop
  *
  * @param processId id of the strategy stopped
  */
  @Override
  public void onStop ( long processId ) {
    logger.info ( "Strategy stopped: " + processId );
  
    if ( testClient.getStartedStrategies().size() == 0 ) {
      logger.info ( "No further strategies remaining; exiting" );
      System.exit ( 0 );
    }
  }
  
  /**
  * Called on successfull connect
  */
  @Override
  public void onConnect() {
    logger.info ( "Connected" );
    lightReconnects = 3;
  }
  
  /**
  * Called on disconnect
  */
  @Override
  public void onDisconnect() {
    logger.warn ( "Disconnected" );
  
    if ( lightReconnects > 0 ) {
      testClient.reconnect();
      --lightReconnects;
    } else {
      try {
        //sleep for 10 seconds before attempting to reconnect
        Thread.sleep ( 10000 );
      } catch ( InterruptedException e ) {
        //ignore
      }
  
      try {
        testClient.connect ( jnlpUrl, userName, password );
      } catch ( Exception e ) {
        logger.error( e.getMessage(), e );
      }
    }
  }
}